package net.sf.midollo.net.cgitunnel.client;

import net.sf.midollo.io.IOStream;
import net.sf.midollo.io.IOStreamFactory;
import net.sf.midollo.net.cgitunnel.CGITunnelConstants;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public class CGITunnelClient implements CGITunnelConstants {

	protected final IOStream ioStream;
	protected final DataInputStream dis;
	protected final DataOutputStream dos;
	protected final String host;
	protected final int port;

	public CGITunnelClient(IOStreamFactory ioStreamFactory, String host, int port) throws IOException {
		this.ioStream = ioStreamFactory.open();
		this.dis = new DataInputStream(this.ioStream.getInput());
		this.dos = new DataOutputStream(this.ioStream.getOutput());
		this.host = host;
		this.port = port;
	}

	public void close() throws IOException {
		this.ioStream.close();
	}

	public void requestCmdOpen() throws IOException {
		this.dos.writeByte(CMD_OPEN);
		this.dos.writeUTF(this.host);
		this.dos.writeInt(this.port);
		this.dos.flush();
	}

	public void requestCmdClose() throws IOException {
		this.dos.writeByte(CMD_CLOSE);
		this.dos.flush();
	}

	public void requestCmdWrite(byte[] buffer, int off, int len) throws IOException {
		this.dos.writeByte(CMD_WRITE);
		this.dos.writeInt(len);
		this.dos.write(buffer, off, len);
		this.dos.flush();
	}

	public int requestCmdRead(byte[] buffer, int off, int len) throws IOException {
		return this.dis.read(buffer, off, len);
	}
}
